// pages/bluetooth/bluetooth.js
var app = getApp
Page({
  data: {
    array: [],
    deviceId: {},
    array: [],
    services: [],
    str: [],
    index: 0,
    number1: "",
    code: '',
    this_write_cid: ''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.openBluetooth()
  },
  onReady: function () {
    // 页面渲染完成

  },
  onShow: function () {
    // 页面显示
    this.startBluetoothDevicesDiscovery()
  },
  onHide: function () {
    // 页面隐藏
    console.log("onHide")
    this.stopBluetoothDevicesDiscovery()
  },
  onunLoad: function () {
    this.closeBluetooth()
  },
  //初始化蓝牙适配器
  openBluetooth: function () {
    var that = this
    that.closeBluetooth()
    wx.openBluetoothAdapter({
      success: function (res) {
        // success
        // wx.showToast({
        //   title: "初始化蓝牙适配器成功",
        //   duration: 2000
        // })
        that.getConnectedBluetoothDevices()
        that.startBluetoothDevicesDiscovery()
        // that.startBluetoothDevicesDiscovery()
      },
    })
  },
  getConnectedBluetoothDevices: function () {
    var that = this
    wx.getConnectedBluetoothDevices({
      services: ["FFF0"],
      success: function (res) {
        console.log("res:", res)
        console.log("res:", res.devices)
        // console.log("res:", res.devices[0].deviceId)
        // console.log("res:", res.devices[0].name)
        var temp1 = that.data.array
        // // console.log("sss", res.devices[0].deviceId)

        for (var i = 0; i < res.devices.length; i++) {
          that.add(temp1, res.devices[i])
        }
      },
    })
  },
  //关闭蓝牙模块
  closeBluetooth: function () {
    wx.openBluetoothAdapter()

    wx.closeBluetoothAdapter({
      success: function (res) {
        // success
        console.log("success" + res)
      }
    })
  },
  //获取本机蓝牙适配器状态
  getBluetoothAdapterState: function () {
    wx.getBluetoothAdapterState({
      success: function (res) {
        // success
        console.log("res:" + res)
        console.log("errMsg:" + res.errMsg)
      }
    })
  },
  //监听蓝牙适配器状态变化事件
  onBluetoothAdapterStateChange: function () {
    wx.onBluetoothAdapterStateChange(function (res) {
      console.log(`adapterState changed, now is`, res)
    })
  },
  // 开始搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery: function () {
    var that = this
    wx.startBluetoothDevicesDiscovery({
      services: ["FFF0"],
      success: function (res) {
        //  console.log(`startBluetoothDevicesDiscovery`, res)
      },
      fail: function (res) {

      },
      complete: function (res) {
        //  console.log(`startBluetoothDevicesDiscovery complete`, res)
        that.onBluetoothDeviceFound()

      }
    })
  },
  // 停止搜寻附近的蓝牙外围设备
  stopBluetoothDevicesDiscovery: function () {
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) {
        console.log("stopBluetoothDevicesDiscovery success", res)
      }
    })
  },
  //获取所有已发现的蓝牙设备
  getBluetoothDevices: function () {
    wx.getBluetoothDevices({
      success: function (res) {
        // success
        console.log(res)
      },
    })
  },
  contains: function (array, deviceId) {
    for (var i = 0; i < array.length; i++) {
      if (array[i].deviceId === deviceId) {
        console.log("=======================")
        return true;
      }
    }
    return false;
  },
  add: function (array1, o) {
    var that = this
    var temp = array1.concat(o)

    temp.sort(function compare(a, b) {
      if (a.RSSI > b.RSSI) {
        return -1;
      }
      return 1;
    })
    that.setData({
      array: temp
    })
    console.log('onBluetoothDeviceFound array', temp)

  },
  remove: function (array, obj) {
    for (var i = 0; i < array.length; i++) {
      if (array[i].deviceId === obj.deviceId) {
        array.splice(1, array[i])
        console.log('remove', obj.name)
      }
    }
  },
  //监听寻找到新设备的事件
  onBluetoothDeviceFound: function () {
    var that = this
    wx.onBluetoothDeviceFound(function (res) {
      // callback
      console.log('onBluetoothDeviceFound', res)
      console.log('onBluetoothDeviceFound', res.devices)
      console.log('onBluetoothDeviceFound object', res.devices[0])
      console.log('onBluetoothDeviceFound name', res.devices[0].name)
      var temp1 = that.data.array
      // console.log("sss", res.devices[0].deviceId)

      if (res.devices[0].name && res.devices[0].RSSI <= 0) {
        res.devices[0].name = that.trim(res.devices[0].name)
        if (!that.contains(temp1, res.devices[0].deviceId)) {
          that.add(temp1, res.devices[0])
        } else {
          that.remove(temp1, res.devices[0])
          that.add(temp1, res.devices[0])
        }
      }

    })
  },
  itemClick: function (e) {
    var that = this
    console.log("Click is " + e.currentTarget.id)
    that.setData({
      deviceId: e.currentTarget.id
    })
    that.createBLEConnection()
    // wx.navigateTo({
    //   url: '../BLEConnect/BLEConnect?deviceId=' + e.currentTarget.id,
    //   success: function (res) {
    //     // success
    //     console.log("success"+res)
    //   },
    //   fail: function (res) {
    //     // fail
    //     console.log("fail"+res)
    //   },
    //   complete: function (res) {
    //     // complete
    //     console.log("complete"+res)
    //   }
    // })

  },
  trim: function (str) {
    // return str.value.replace(/(^\s+)|(\s+$)/g, "")
    // str = str.replace(/[\r\n]/g,"")
    return str.replace(/[ ]/g, "").replace(/[\r\n]/g, "")
  },
  //连接低功耗蓝牙设备
  createBLEConnection: function () {
    console.log("createBLEConnection")
    var that = this
    var number = that.data.number1 + "\n"
    var deviceId = that.data.deviceId
    that.setData({
      number1: number + "正在连接" + deviceId
    })
    wx.openBluetoothAdapter({
      success: function (res) {
        wx.createBLEConnection({
          deviceId: that.data.deviceId,
          success: function (res) {
            // success
            console.log(res)
            var number = that.data.number1 + "\n"
            that.setData({
              number1: number + "连接成功",              
            })

            that.getBLEDeviceServices()
            wx.showToast({
              title: '连接成功',
              icon: 'loading'
            })
            getApp().globalData.isLink=true
             setTimeout(function () { wx.navigateBack() }, 2000)
          },
          fail() {
            wx.showToast({
              title: '连接失败',
              icon: 'loading'
            })
          },
          complete: function (res) {
            console.log("complete" + res)

          }
        })
      },
    })

  },
  //断开与低功耗蓝牙设备的连接
  closeBLEConnection: function () {
    var that = this
    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success: function (res) {
        console.log(res)
        wx.closeBluetoothAdapter({
          success: function (res) {

          },
        })
      }
    })
  },
  //监听低功耗蓝牙连接的错误事件，包括设备丢失，连接异常断开等等
  onBLEConnectionStateChanged: function () {
    wx.onBLEConnectionStateChanged(function (res) {
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
    })
  },
  //获取蓝牙设备所有 service（服务）
  getBLEDeviceServices: function () {
    var that = this
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success: function (res) {
        // success
        console.log('device services:', res)
        console.log('device services:', res.services)
        console.log('device services:', res.services.length)
        that.setData({
          services: res.services
        })
        that.getBLEDeviceCharacteristics()
      },
      fail: function (res) {
        // fail
      },
      complete: function (res) {
        // complete
      }
    })
  },
  //获取蓝牙设备所有 characteristic（特征值）
  getBLEDeviceCharacteristics: function () {
    var that = this
    var that_services = that.data.services
    for (var i = 0; i < that_services.length; i++) {
      var that_service_uuid = that_services[i].uuid
      console.log("that_services[i].uuid = ", that_services[i].uuid)
      console.log("that_services[i].uuid  ", that_service_uuid == "0000FFF0-0000-1000-8000-00805F9B34FB")
      if (that_service_uuid == "0000FFF0-0000-1000-8000-00805F9B34FB" || that_service_uuid == "0000fff0-0000-1000-8000-00805f9b34fb") {
        wx.getBLEDeviceCharacteristics({
          deviceId: that.data.deviceId,
          serviceId: that_service_uuid,
          success: function (res) {
            // success
            console.log("getBLEDeviceCharacteristics", res)
            console.log("getBLEDeviceCharacteristics", res.characteristics)
            console.log("getBLEDeviceCharacteristics", res.characteristics[0])
            var that_array = that.data.array
            // var that_characteristics = res.characteristics
            // that_array = that_array.concat([{serviceId=that_services[i].uuid,characteristics=res.characteristics}])

            // that.setData({
            //   array: that_array.concat([{ serviceId: that_service_uuid, characteristics: res.characteristics }])
            // })
          },
          fail: function (res) {
            // fail
          },
          complete: function (res) {
            // complete
            console.log("getBLEDeviceCharacteristics ", res.length)
            for (var i = 0; i < res.characteristics.length; i++) {
              var that_characteristic = res.characteristics[i]
              if ((that_characteristic.uuid == "0000FFF4-0000-1000-8000-00805F9B34FB" || that_characteristic.uuid == "0000fff4-0000-1000-8000-00805f9b34fb") && that_characteristic.properties.notify && that_characteristic.properties.read) {
                that.notifyBLECharacteristicValueChanged(that_characteristic.uuid)
              }
              if ((that_characteristic.uuid == "0000FFF1-0000-1000-8000-00805F9B34FB" || that_characteristic.uuid == "0000fff1-0000-1000-8000-00805f9b34fb") && that_characteristic.properties.write) {
                that.setData({
                  this_write_cid: that_characteristic.uuid
                })
                console.log("this_write_cid", that.data.this_write_cid)
              }
            }
            // that.notifyBLECharacteristicValueChanged()
          }
        })
      }
    }
  },
  notifyBLECharacteristicValueChanged: function (cid) {
    var that = this
    wx.notifyBLECharacteristicValueChanged({
      deviceId: that.data.deviceId,
      serviceId: "0000FFF0-0000-1000-8000-00805F9B34FB",
      characteristicId: cid,
      state: true,
      success: function (res) {
        // success
        console.log(res)
      },
      fail: function (res) {
        // fail
      },
      complete: function (res) {
        // complete
        console.log('complete', res)
        var number = that.data.number1 + "\n"
        that.setData({
          number1: number + "目前状态可扫描\n请扫描："
        })
        that.onBLECharacteristicValueChange()
      }
    })
  },
  onBLECharacteristicValueChange: function () {
    var that = this
    wx.onBLECharacteristicValueChange(function (res) {
      console.log('characteristic ${res.characteristicId} has changed, now is', res.value)
      console.log('byteLength=', res.value.byteLength)
      that.getCodeByte(res.value)
      // that.getCurrentNumberString(that.data.str)
      // wx.readBLECharacteristicValue({
      //   // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      //   deviceId: that.data.deviceId,
      //   // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      //   serviceId: that.data.array[0].serviceId,
      //   // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      //   characteristicId: cId,
      //   success: function (res) {
      //     console.log('readBLECharacteristicValue:', res)
      //   }
      // })
    })

  },
  getCodeByte: function (arrayBuffer) {
    var that = this
    var dataView = new DataView(arrayBuffer)
    for (var i = 0; i < arrayBuffer.byteLength; i++) {
      if (arrayBuffer.byteLength > 3 && dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) {
        if (i > 3 && i < arrayBuffer.byteLength - 3) {
          that.data.index = i - 4
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      } else if (arrayBuffer.byteLength > 3 && dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01) {
        if (i > 3 && dataView.getUint8(i) != 121) {
          that.data.index = i - 4
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      }

      else if (dataView.getUint8(0) != 0x40 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) {
        if (i < arrayBuffer.byteLength - 3) {
          that.data.index++
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      } else {
        if (dataView.getUint8(i) != 121) {
          that.data.index++
          that.data.str[that.data.index] = dataView.getUint8(i)
        }
      }
    }
    if ((dataView.getUint8(0) != 0x40 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A) || (dataView.getUint8(0) == 0x40 && dataView.getUint8(2) == 0x53 && dataView.getUint8(3) == 0x01 && dataView.getUint8(arrayBuffer.byteLength - 1) == 0x2A)) {
      that.getCurrentNumberString(that.data.str)
    }
  },
  getCurrentNumberString: function () {
    console.log("----------22222")
    var that = this
    var tostring = ""

    // if (array.length > 4 && array[0] == 0x40 && array[2] == 0x53 && array[3] == 0x01 && array[that.data.index] == 0x2A) {
    tostring = String.fromCharCode.apply(String, that.data.str);
    console.log(tostring);
    console.log(tostring.length);
    var number = that.data.number1
    that.setData({
      str: [],
      number1: number + "\n" + tostring
    })
    //  getApp().getCode(tostring)
    console.log("number1-----" + that.data.number1);
    getApp().getCode(tostring)
    // }
  },
  writeBLECharacteristicValue: function (cId) {
    var that = this
    // 向蓝牙设备发送一个0x00的16进制数据
    var buffer = new ArrayBuffer(1)
    var dataView = new DataView(buffer)
    dataView.setUint8(0, 0)
    wx.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId: that.data.deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: "0000FFF0-0000-1000-8000-00805F9B34FB",
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: cId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      success: function (res) {
        console.log('writeBLECharacteristicValue success', buffer)
        console.log('writeBLECharacteristicValue success', res.errMsg)
      }
    })
  },
  cl: function () {
    var that = this
    var buffer = new ArrayBuffer(7)
    var dataView = new DataView(buffer)
    dataView.setUint8(0, 0x40)
    dataView.setUint8(1, 0x03)
    dataView.setUint8(2, 0x53)
    dataView.setUint8(3, 0xF0)
    dataView.setUint8(4, 0x00)
    dataView.setUint8(5, 0x46)
    dataView.setUint8(6, 0x2A)
    // console.log("this_write_cid", that.data.this_write_cid)      
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: "0000FFF0-0000-1000-8000-00805F9B34FB",
      characteristicId: that.data.this_write_cid,
      value: buffer,
      success: function (res) {

        console.log("writeBLECharacteristicValue", res)
      },
    })
    this.closeBLEConnection()
  },
  conn: function () {
    this.createBLEConnection()
  }
})